class TeacherMgrController {
    def createBlogService
    def authenticateService
    def teacherSearcheService
    def teacherService
    def valueLevelService
    def index = { }
    /**
    * 组织设置初始化页面
    */
    def organizeset = {
        // def schoolList = Organize.findAllBySchool(School.get(session.schoolID))
        Teacher teacherInstance = Teacher.get(params.id)
        log.info(session.school.name)
        log.info(teacherInstance.name)
        def organizeList = Organize.findAllBySchool(session.school)
        [organizeList:organizeList,teacherInstance:teacherInstance,haveOrganize:teacherInstance.organize]
    }

    /**
    * 组织设置具体功能
    */
    def organizesetSave = {
        log.info("params.organizeSelect"+params.organizeSelect)
        def organizes = params.organizeSelect
        
        def teacherInstance = Teacher.get(params.teacherID)
        teacherInstance.organize.toList().each { it.removeFromTeachers(teacherInstance) }
        if(organizes){
            organizes.each{
                teacherInstance.addToOrganize(Organize.get(it))
            }
            teacherInstance.save()
        }
        flash.message = "组织设置成功"
        //render(view:"organizeset",model:[teacherInstance:teacherInstance,organizeList:organizeList,haveOrganize:teacherInstance.organize])
        if(!params.searchFlag){
            return redirect(action:"list", controller:"teacher")
        }else{
            return redirect(action: "teacherSearchList",controller:"teacherMgr")
        }
    }

   /**
    * 科目设置初始化
    */
    def courseset = {
        // def schoolList = Organize.findAllBySchool(School.get(session.schoolID))
        Teacher teacherInstance = Teacher.get(params.id)
        if(!teacherInstance || teacherInstance.authorities.size() == 0){
            flash.message = "请先为 ${teacherInstance?.name} 设置角色"
            if(!params.searchFlag){
                return redirect(action:"list", controller:"teacher")
            }else{
                return redirect(action: "teacherSearchList",controller:"teacherMgr")
            }
        }
        def teacherRole = authenticateService.securityConfig.security.teacherRole
        def isTeacherRole = teacherInstance.authorities.any{
            it.authority == teacherRole
        }
        if(!isTeacherRole){
            flash.message = "${teacherInstance?.name} 必须有代课老师的角色才能设置科目！"
            if(!params.searchFlag){
                return redirect(action:"list", controller:"teacher")
            }else{
                return redirect(action: "teacherSearchList",controller:"teacherMgr")
            }
        }
        log.info(teacherInstance.name)
        def courselst = new ArrayList()
        def levelList = School.get(session.school.id).level
        levelList.each{
             courselst.addAll(valueLevelService.getCodeListByLevel(it))
        }
        courselst.unique()
        
        

        //def organizeList = Organize.findAllBySchool(School.get("1"))
        [teacherInstance:teacherInstance,courselst:courselst,haveCourse:teacherInstance.course]
    }

    /**
    * 科目设置具体功能
    */
    def coursesetSave = {    
        log.info("params.courseSelect"+params.courseSelect)
        def courses = params.courseSelect
        def teacherInstance = Teacher.get(params.teacherID)
        teacherInstance.course.clear()
        if(courses != "~"){
            if(courses){
                courses.each{
                    if(it != "~"){
                        teacherInstance.addToCourse(it)
                    }
                }
                flash.message = "科目设置成功"
                teacherInstance.save()
            }
        }
        if(!params.searchFlag){
            return redirect(action:"list", controller:"teacher")
        }else{
            return redirect(action: "teacherSearchList",controller:"teacherMgr")
        }
        
    }

    

    // 初始化角色设置
      def roleset = {
          Teacher teacherInstance = Teacher.get(params.id)
            if (!teacherInstance) {
              flash.message = "教师没有找到！"
              if(!params.searchFlag){
                    return redirect(controller: "teacher", action: "list")
              }else{
                    return redirect(action: "teacherSearchList",controller:"teacherMgr")
              }
              return
            }
            
            return getPersonRole(teacherInstance)
      }

    //  保存角色的设置
      def rolesetSave = {
            def person = Teacher.get(params.teacherID)
            Role.findAll().each { it.removeFromPeople(person) }
            flash.message = "设置成功"
            addRoles(person)
            if(!params.searchFlag){
                return redirect(action:"list", controller:"teacher")
            }else{
                return redirect(action: "teacherSearchList",controller:"teacherMgr")
            }
      }

      // 私有方法，将用户加入到某个角色中去
      private void addRoles(person) {
        for (String key in params.keySet()) {
          if (key.contains('ROLE') && 'on' == params.get(key)) {
            Role.findByAuthority(key).addToPeople(person)
          }
        }
      }
      // 私有方法，取得系统中所有的角色
      private Map getPersonRole(person) {
        List roles = Role.list()
        roles.sort {r1, r2 ->
          r1.authority <=> r2.authority
        }
        Set userRoleNames = []
        for (role in person.authorities) {
          userRoleNames << role.authority
        }

        LinkedHashMap<Role, Boolean> roleMap = [:]
        def adminRole = authenticateService.securityConfig.security.adminRole
        for (role in roles) {
          if(role.authority != adminRole){
            roleMap[(role)] = userRoleNames.contains(role.authority)
          }
        }
        return [teacherInstance: person, roleMap: roleMap]
      }

    // 开启和停用教师
    def goswitch = {
        if (params.id) {
            def teacher = Teacher.get(params.id)
            teacher.enabled = !teacher.enabled
            teacher.save(flush: true)
        }
        if(!params.searchFlag){
                return redirect(controller: "teacher", action: "list")
          }else{
                return redirect(action: "teacherSearchList",controller:"teacherMgr")
          }
    }

    //重置教师的密码为123456
    def resetPassword = {
        if (params.id) {
            def teacher = Teacher.get(params.id)
            teacher.passwd = authenticateService.encodePassword(grailsApplication.config.grails.default.teacher.passwd)
            teacher.save(flush: true)
        }
        if(!params.searchFlag){
            redirect(action: "list" , controller: "teacher")
        }else{
            redirect(action: "teacherSearchList",controller:"teacherMgr")
        }
        
    }

// 顶部信息移动到 layout/top方法中
//    def getLoginTeacherRole = {
//       
//        if(session.teacherID){
//                def roles = Teacher.get(session.teacherID).authorities
//                log.info(roles)
//                [roles: roles]
//        }
//    }
    def createblog = {
          def teacherInstance 
          if (params.id) {
            teacherInstance = Teacher.get(params.id)
        }else{
             flash.message = "没有找到此教师！"
              if(!params.searchFlag){
                    return redirect(controller: "teacher", action: "list")
              }else{
                    redirect(action: "teacherSearchList",controller:"teacherMgr")
              }
             
        }
         if(createBlogService.sendCreateBlog(teacherInstance,grailsApplication.config.grails.default.blog.create.uri)){
                teacherInstance.hasBlog = true
                teacherInstance.save(flush:true)
                flash.message = "创建教师博客成功！"
         }else{
                flash.message = "创建教师博客失败，请重试或联系管理员！"
         }

          if(!params.searchFlag){
                return redirect(controller: "teacher", action: "list")
          }else{
                return redirect(action: "teacherSearchList",controller:"teacherMgr")
          }
     }

     def changePassword = {
     
     }

     def saveChangePassword = {
        def person = Teacher.get(authenticateService.userDomain().id)
        if(person.passwd == authenticateService.encodePassword(params.oldPassword)){
            if (params.passwd.equals(params.confirmPasswd)) {
			    person.passwd = authenticateService.encodePassword(params.passwd)
                if (person.save()) {
                    flash.message = "密码修改成功"
                    redirect action: changePassword
                }else {
                    return render(view:"changePassword")
                }
		    }else{
                person.errors.rejectValue('passwd','新密码与确认密码不相同')
                return render(view:"changePassword",model:[person:person])
            }
        }else{
            person.errors.rejectValue('passwd','原密码不正确')
            return render(view:"changePassword",model:[person:person])
        }
     }
    
     // 教师查询
     def teacherSearchList = {
        if(params.isSearch){
            teacherSearcheService.searcheTeacherInit(params.name,params.sex,params.role,params.staff,params.degree,params.features,session.school)
        }
        return teacherSearcheService.searchTeacherList()
     }
    
     // 教师工作量统计
     def courseInfo = {
        def schoolTeacherList = teacherService.getSchoolAndAbeldTeacher(session.school);

        [schoolTeacherList:schoolTeacherList]
     }

     def list = {
        def schoolMasterRole = authenticateService.securityConfig.security.schoolMasterRole
        def teacherList = Teacher.findAllBySchool(session.school)
        def isSchoolMaster = Teacher.get(authenticateService.userDomain().id).authorities.any{
            it.authority == schoolMasterRole
        }
        log.info(teacherList.size()+"qqqqq")
        if(!isSchoolMaster){
            teacherList = teacherList.grep{
                it.authorities.any{ elem ->
                    elem.authority != schoolMasterRole
                } 
            }
        }
        [teacherInstanceList:teacherList]
     }
}
